/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import dao.ChiTietHoaDonDAO;
import dao.CuaHangDAO;
import dao.SanPhamCuaHangDAO;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;
import org.apache.log4j.Logger;
import pojo.BaoCaoDoanhThu;
import pojo.CuaHang;
import pojo.SanPhamCuaHang;

/**
 *
 * @author 0
 */
public class ThongKeDoanhThuGUI extends javax.swing.JPanel {

    /**
     * Creates new form ThongKeDoanhThuGUI
     */
    private static Logger logger = Logger.getLogger(ThongKeDoanhThuGUI.class);
    private JErrorProvider errorProvider;
    
    public ThongKeDoanhThuGUI() throws Exception {
        initComponents();
        errorProvider=new JErrorProvider();
        SetTabOrder();
        Autoload();
    }
    
    private void SetTabOrder(){
        IndexedFocusTraversalPolicy indexedFocusTraversalPolicy=new IndexedFocusTraversalPolicy();
        indexedFocusTraversalPolicy.addIndexedComponents(new Component[]{cboCuaHang,dtNgayFrom,dtNgayTo,btnBaoCao});
        setFocusTraversalPolicy(indexedFocusTraversalPolicy);
    }
    
    private void Autoload() throws Exception{
        List<CuaHang> cuaHangs = (List<CuaHang>) CuaHangDAO.LayDanhSach(CuaHang.class, MainGUI.nguoiDung);
        Collections.sort(cuaHangs, new Comparator<CuaHang>() {
            @Override
            public int compare(CuaHang o1, CuaHang o2) {
                return o1.getTenCuaHang().compareTo(o2.getTenCuaHang());
            }
        });
        Utility.SetDataSourceInCombo(cuaHangs, cboCuaHang);
        cboCuaHang.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (value instanceof CuaHang) {
                    CuaHang cuaHang = (CuaHang) value;
                    setText(cuaHang.getTenCuaHang());
                }
                return this;
            }
        });
        cboCuaHang.setSelectedIndex(-1);
    }
    
    private int CheckDataBeforeBaoCao(){
        int dem=0;
        if(cboCuaHang.getModel().getSelectedItem()==null){
            errorProvider.setError(cboCuaHang, "required");
            dem++;
        }
        if(dtNgayFrom.getDate()==null){
            errorProvider.setError(dtNgayFrom, "required");
            dem++;
        }
        if(dtNgayTo.getDate()==null){
            errorProvider.setError(dtNgayTo, "required");
            dem++;
        }
        return dem;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnBaoCao = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        cboCuaHang = new javax.swing.JComboBox();
        dtNgayFrom = new org.jdesktop.swingx.JXDatePicker();
        dtNgayTo = new org.jdesktop.swingx.JXDatePicker();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        btnBaoCao.setText("Báo cáo");
        btnBaoCao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBaoCaoActionPerformed(evt);
            }
        });

        jLabel3.setText("Cửa hàng");

        jLabel1.setText("Ngày từ");

        jLabel2.setText("đến");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cboCuaHang, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(dtNgayFrom, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(27, 27, 27)
                                .addComponent(jLabel2))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(110, 110, 110)
                                .addComponent(btnBaoCao)))
                        .addGap(18, 18, 18)
                        .addComponent(dtNgayTo, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(30, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cboCuaHang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dtNgayFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(dtNgayTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnBaoCao)
                .addContainerGap(19, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnBaoCaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBaoCaoActionPerformed
        try {
            // TODO add your handling code here:
            if(CheckDataBeforeBaoCao()>0){
                return;
            }
            CuaHang cuaHang=(CuaHang) cboCuaHang.getModel().getSelectedItem();
            List<Object[]> list = ChiTietHoaDonDAO.LayDanhSachBaoCaoDoanhThu(dtNgayFrom.getDate(),dtNgayTo.getDate(),cuaHang.getId());
            ArrayList<BaoCaoDoanhThu> baoCaoDoanhThus=new ArrayList<>();
            Double S=0.0;
            for(int i=0;i<list.size();i++){
                BaoCaoDoanhThu baoCaoDoanhThu=new BaoCaoDoanhThu();
                baoCaoDoanhThu.setDonGia((Double)(list.get(i)[3]));
                baoCaoDoanhThu.setMaSanPhamCuaHang((Integer)(list.get(i)[0]));
                baoCaoDoanhThu.setTenSanPham((String)(list.get(i)[1]));
                baoCaoDoanhThu.setSoLuong((Long)(list.get(i)[2]));
                baoCaoDoanhThu.setTongTien((Double)(list.get(i)[4]));
                S+=baoCaoDoanhThu.getTongTien();
                baoCaoDoanhThus.add(baoCaoDoanhThu);
            }
            List<SanPhamCuaHang> sanPhamCuaHangs=SanPhamCuaHangDAO.LayDanhSachBaoCaoTon(cuaHang.getId());
            for(SanPhamCuaHang sanPhamCuaHang:sanPhamCuaHangs){
                boolean flag=false;
                for(BaoCaoDoanhThu baoCaoDoanhThu:baoCaoDoanhThus){
                    if(baoCaoDoanhThu.getMaSanPhamCuaHang()==sanPhamCuaHang.getId()){
                        flag=true;
                        break;
                    }
                }
                if(!flag){
                    BaoCaoDoanhThu baoCaoDoanhThu=new BaoCaoDoanhThu();
                    baoCaoDoanhThu.setDonGia(sanPhamCuaHang.getSanPham().getDonGia());
                    baoCaoDoanhThu.setMaSanPhamCuaHang(sanPhamCuaHang.getId());
                    baoCaoDoanhThu.setSoLuong(Long.valueOf(0));
                    baoCaoDoanhThu.setTenSanPham(sanPhamCuaHang.getTenCuaHang());
                    baoCaoDoanhThu.setTongTien(0.0);
                    baoCaoDoanhThus.add(baoCaoDoanhThu);
                }
            }
            
            String reportName="src\\BaoCaoDoanhThu.jrxml";
            HashMap map=new HashMap();
            JasperReport report = JasperCompileManager.compileReport(reportName);
            map.put("DATASOURCE", baoCaoDoanhThus);
            map.put("TONGDOANHTHU", S);
            map.put("NGAYFROM", dtNgayFrom.getDate());
            map.put("NGAYTO", dtNgayTo.getDate());
            map.put("CUAHANG", cuaHang.getTenCuaHang());
            JasperPrint fillReport = JasperFillManager.fillReport(report, map,new net.sf.jasperreports.engine.JREmptyDataSource());
            JasperViewer jv=new JasperViewer(fillReport, false);
            jv.setVisible(true);
        } catch (Exception ex) {
            logger.error(new Date().toString(), ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_btnBaoCaoActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBaoCao;
    private javax.swing.JComboBox cboCuaHang;
    private org.jdesktop.swingx.JXDatePicker dtNgayFrom;
    private org.jdesktop.swingx.JXDatePicker dtNgayTo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    // End of variables declaration//GEN-END:variables
}
